<template>
  <view class="container">
    <!-- Table Header with Sorting -->
    <view class="table-header">
      <view class="header-left"></view>
      <view class="header-right">
        <view 
          class="header-item" 
          @tap="sortBy('area')"
        >
          <text>面积</text>
          <view class="sort-icons">
            <text class="sort-icon" :class="{'active': sortField === 'area' && sortOrder === 'asc'}">▲</text>
            <text class="sort-icon" :class="{'active': sortField === 'area' && sortOrder === 'desc'}">▼</text>
          </view>
        </view>
        <view 
          class="header-item" 
          @tap="sortBy('status')"
        >
          <text>是否出租</text>
          <view class="sort-icons">
            <text class="sort-icon" :class="{'active': sortField === 'status' && sortOrder === 'asc'}">▲</text>
            <text class="sort-icon" :class="{'active': sortField === 'status' && sortOrder === 'desc'}">▼</text>
          </view>
        </view>
      </view>
    </view>

    <!-- Listing Cards -->
   <scroll-view 
         scroll-y 
         class="listing-container"
         @scrolltolower="loadMore"
         @refresherpulling="onPulling"
         @refresherrefresh="onRefresh"
         :refresher-enabled="true"
         :refresher-triggered="isRefreshing"
         :show-scrollbar="false"
		 style="height: 1400rpx;"
       >
         <view 
           v-for="item in sortedListings" 
           :key="item.id" 
           class="listing-card"
           hover-class="listing-card-hover"
           @tap="navigateToDetail(item.id)"
         >
           <image :src="imgurl+item.imgUrl" mode="aspectFill" class="listing-image"/>
           <view class="listing-info">
             <view class="listing-main">
               <text class="listing-title">{{item.title}}</text>
               <view class="listing-location">
                 <text class="location-icon">📍{{item.address}}</text>
                 <!-- <text style="word-break: break-all;">{{item.address}}</text> -->
               </view>
             </view>
             <view class="listing-details">
               <text class="listing-area">面积:{{item.area}}㎡</text>
               <text :class="['rental-status', item.status ? 'available' : 'rented']">
                 {{item.status==1 ? '可租' : '已租'}}
               </text>
             </view>
           </view>
         </view>
         
         <!-- Loading States -->
         <view class="loading-state" v-if="loadingMore">
           <view class="loading-spinner"></view>
           <text>加载中...</text>
         </view>
         
         <view class="no-more" v-if="noMore">
           <text>没有更多数据了</text>
         </view>
       </scroll-view>
  </view>
</template>

<script>
	import config from '../../config';
	import {listHouses} from '@/api/homestay.js'
export default {
  data() {
    return {
      listings: [
              // 更多房间数据...
            ],
	  imgurl: config.staticUrl,
	  isRefreshing: false,
	  loadingMore: false,
	  noMore: false,
	  totalPages: 1,//总页码
	  sortField: '',
	  sortOrder: 'asc',
	  queryParams: {
		  pageNum: 1,//当前页码
		  pageSize: 10,//每页多少条
	  }
    }
  },
  computed: {
    sortedListings() {
      if (!this.sortField) return this.listings
      
      return [...this.listings].sort((a, b) => {
        let compareResult = 0
        
        if (this.sortField === 'area') {
          compareResult = a.area - b.area
        } else if (this.sortField === 'status') {
          compareResult = (a.status === b.status) ? 0 : a.status ? 1 : -1
        }
        
        return this.sortOrder === 'asc' ? compareResult : -compareResult
      })
    }
  },
  methods: {
    // 初始加载数据
    fetchListings(reset = false) {
          if (reset) {
            this.queryParams.pageNum = 1
            this.listings = []
            this.noMore = false
          }
    
          // console.log("queryParams:",this.addQueryParams(this.queryParams,this.sortField,this.sortOrder))
          listHouses(this.addQueryParams(this.queryParams,this.sortField,this.sortOrder)).then(response => {
                  const data = response.rows;
                  this.totalPages = response.total;
          		    
          		if (reset) {
          		  this.listings = data
          		} else {
          		  this.listings = [...this.listings, ...data]
          		}
          		    
          		this.noMore = this.queryParams.pageNum >= this.totalPages
				// console.log("=====",this.noMore)
           });
        },
    
        // 下拉刷新
        onRefresh() {
          this.isRefreshing = true
          this.fetchListings(true)
		  //关闭加载状态 (转动的圈)，需要一点延时才能关闭
		   setTimeout(() => {
		       this.isRefreshing = false
		    },1000)
			// console.log("isRefreshing=====",this.isRefreshing)
        },
    
        // 上拉加载更多
        loadMore() {
          if (this.loadingMore || this.noMore) return
          
          this.loadingMore = true
          this.queryParams.pageNum += 1
          this.fetchListings()
		  //关闭加载状态 (转动的圈)，需要一点延时才能关闭
		   setTimeout(() => {
		       this.loadingMore = false
		    },1000)
        },
    
        // 下拉中
        onPulling(e) {
          // 可以根据下拉距离添加一些动画效果
        },
    
        // 排序处理
        sortBy(field) {
          if (this.sortField === field) {
            this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc'
          } else {
            this.sortField = field
            this.sortOrder = 'asc'
          }
          
          // 重新加载数据
         this.fetchListings(true)
        },
    
        navigateToDetail(id) {
          uni.navigateTo({
            url: `/pages/homestay/detail?id=${id}`
          })
        },
		
		// 添加查询参数
		addQueryParams(params, sortField, sortOrder,propName) {
		   let search = params;
		   search.params = typeof (search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
		   if (typeof (propName) === 'undefined') {
		     search.params['sortField'] = sortField;
		     search.params['sortOrder'] = sortOrder;
		   } else {
		     search.params['sortField' + propName] = sortField;
		     search.params['sortOrder' + propName] = sortOrder;
		   }
		   return search;
		 }
      },
      onLoad() {
        this.fetchListings()
      }
}
</script>

<style lang="scss">
.container {
  padding: 20rpx;
  background: #f8f9fa;
}

.table-header {
  display: flex;
  padding: 20rpx;
  background: #fff;
  border-radius: 12rpx 12rpx 0 0;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 1;
  
  .header-left {
    width: 200rpx;  // Match image width plus some padding
    flex-shrink: 0;
  }
  
  .header-right {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    gap: 30rpx;
    padding-right: 20rpx;
    
    .header-item {
      width: 150rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10rpx;
      font-size: 28rpx;
      color: #666;
      cursor: pointer;
      
      .sort-icons {
        display: flex;
        flex-direction: column;
        margin-left: 6rpx;
        
        .sort-icon {
          font-size: 20rpx;
          line-height: 1;
          color: #ccc;
          
          &.active {
            color: #1890ff;
          }
        }
      }
    }
  }
}

.listing-container {
  .listing-card {
    display: flex;
    background: #fff;
    margin-bottom: 20rpx;
    border-radius: 12rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    
    &-hover {
      transform: translateY(-2rpx);
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
    }
    
    .listing-image {
      width: 200rpx;
      height: 200rpx;
      flex-shrink: 0;
      object-fit: cover;
    }
    
    .listing-info {
      flex: 1;
      padding: 20rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      
      .listing-main {
        .listing-title {
          font-size: 32rpx;
          font-weight: 600;
          color: #333;
          margin-bottom: 12rpx;
        }
        
        .listing-location {
          display: flex;
          align-items: center;
          gap: 8rpx;
          font-size: 26rpx;
          color: #666;
          
          .location-icon {
            font-size: 24rpx;
          }
        }
      }
      
      .listing-details {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        gap: 150rpx;
        margin-right: 150rpx;
        
        .listing-area {
          width: 150rpx;
          text-align: center;
          font-size: 28rpx;
          color: #333;
        }
        
        .rental-status {
          width: 150rpx;
          text-align: center;
          padding: 8rpx 0;
          border-radius: 6rpx;
          font-size: 26rpx;
          font-weight: 500;
          
          &.available {
            background: #e6f7ff;
            color: #1890ff;
            border: 1rpx solid #91d5ff;
          }
          
          &.rented {
            background: #fff1f0;
            color: #ff4d4f;
            border: 1rpx solid #ffa39e;
          }
        }
      }
    }
  }
}
</style>